<?php

/**
 * Created by PhpStorm.
 * User: chenqinglin
 * Date: 17-8-5
 * Time: 上午9:34
 * 主要实现旧系统订单推送相关功能
 */
class Apievent extends MY_Controller
{


    const KEY = 'base64:Uzf3f19BuU0qckBx6MgYoEo/Nxzmvv5TQ1nbE1zKr1Y=';

    public function __construct()
    {
        parent::__construct();


    }

    /**
     * 返回绑定用户信息
     * @param $username　用户名
     * @param $pwd　密码
     */
    public function getaccount()
    {

        if (!uc_authcode($this->input->get('sign'), 'DECODE')) {
            log_message('error', 'getaccount end '.$this->input->get('sign'));
            return;
        }

        $username = $this->input->post('username');
        $password = $this->input->post('password');
        log_message('error', 'getAccount ' . $username . ' pwd ' . $password);

        $where = "me_username='$username' OR me_phone='$username' AND me_status=1";
        $result = array();
        $this->db->select('me_id,me_username,me_pass,me_phone,me_status')->from('merchant')->where($where);
        $result = $this->db->get()->result_array();
        log_message('error', 'getAccount ' . $username . ' pwd ' . $password . $this->db->last_query());

        if (count($result) == 1 && $result[0]['me_pass'] == md5($password)) {
            log_message('error', 'getAccount suc ' . $username);
            $this->renderJson(Apievent::SUC, Apievent::SUC_MSG, $result[0]['me_id']);
        } else {
            log_message('error', 'getAccount fail ' . $username);
            $this->renderJson(Apievent::FAIL, '用户名或者密码错误', $username);
        }

    }

    /**
     * @param $data订单内容
     */
    public function createorder($data)
    {

        if (!uc_authcode($this->input->get('sign'), 'DECODE')) {
            return;
        }

        log_message('error', 'createOrder begin ');
        $ret = $this->parserDataCreateOrder($data);
        $this->renderJson($ret? Apievent::SUC:Apievent::FAIL, $ret? Apievent::SUC_MSG:Apievent::FAIL, $data);
    }


    const SUC = 200;
    const FAIL = 400;
    const SUC_MSG = "成功";
    const FAIL_MSG = "失败";

    public function renderJson($code, $message, $data)
    {
        if ($message === null) {
            $message = (String)status($code);
        }

        if (is_array($data) || is_object($data)) {
            $retData = [
                'code' => (int)$code,
                'message' => $message,
                'data' => $data,
                'timestamp' => time(),
            ];
        } else {
            $_data = json_decode($data, true);
            $retData = [
                'code' => (int)$code,
                'message' => $message,
                'data' => is_array($_data) ? $_data : $data,
                'timestamp' => time(),
            ];
        }


        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($retData));

    }


    /**
     * CREATE TABLE `orders` (
     * `o_id` int(10) UNSIGNED NOT NULL,
     * `o_number` 编号
     * `o_checknumber` 核销单号，
     * `o_sender`  派单客服姓名,
     * `o_me_id`  商家ID,
     * `o_master` 派送抢单师傅的ID,
     * `o_masterlist` 派送抢单师傅的ID，
     * `o_prostate` 订单状态（1待接受 2执行中 3师傅已拒绝 4已完成 5退款中 6待派送 7待补款 8已取消 9待支付 10拒绝报价 11待报价）,
     * `o_refundstate` 退款之前的订单状态，
     * `o_tracestate` 订单预约异常状态,
     * `o_otracestate` 订单预约异常之前状态,
     * `o_mastate` 师傅操作异常  0正常 1异常,
     * `o_mepaystate`  商家支付状态,
     * `o_paystate` 师傅结算状态（1未结算 2已结算）,
     * `o_createtime` 派单时间,
     * `o_paytime` 支付时间,
     * `o_meettime` 接单时间,
     * `o_couponmoney`使用优惠券减去的金额,
     * `o_cid` 优惠券ID,
     * `o_dismoney` 配送的费用,
     * `o_trueprice`  真实价格 商家价格,
     * `o_price` 师傅价格,
     * `o_ycprice` 异常价格,
     * `o_ycmarke`异常内容,
     * `o_customer` 客户姓名,
     * `o_custphone` 客户电话,
     * `o_custaddress` 客户地址,
     * `o_memark` 客户信息备注,
     * /******************************************************
     * `o_cargo` 货品名称 已不用,
     * `o_cargoimg` 货品图片url 已不用,
     * `o_cargolistid` 货品的产品库ID,
     * `o_cargolistcat` 货品类目,
     * `o_cargolistname` 货品名称新的，旧的已不用,
     * `o_cargolistps` 货品的备注,
     * `o_cargolistnum` 货品的数量,
     * `o_cargolistimg` 货品的图片,
     * `o_cargolistprice` 货品的价格,
     * /******************************************************
     * `o_service` 服务内容,
     * `o_standard` 服务标准,
     * `o_finishtime` 完成时间,
     * `o_elevator` 楼梯类型（1电梯 2步梯）,
     * `o_floor` 楼层,
     * `o_servicecategory` 服务类目(1家具 2其他),
     * `o_servicetype` 服务类型（1配送安装,
     * `o_kefumark` 客服备注,
     * `o_logistatus` 物流状态 ,
     * `o_logisticsmoney` 垫付物流费,
     * `o_logisticsnumber`物流单号,
     * `o_logisticsnum` 物流数量,
     * `o_logistiaddress` 物流地址,
     * `o_logisname` 收货人姓名,
     * `o_logimark` 物流备注,
     * `o_logiphone` 物流电话,
     * `o_feedback` 反馈,
     * `o_refuseinfo` 拒绝的信息,
     * `o_add_time` int(10) NOT NULL,
     * `o_upd_time` int(10) NOT NULL DEFAULT '0'
     * ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
     */
    public function parserDataCreateOrder($data)
    {
        log_message('error', 'parserDataCreateOrder ' . ($data) . 'service_type ');
        /**
         * 创建订单order相关信息
         */
        $me_id = $this->input->post('new_me_id');
        $me_name=$this->session->userdata('me_username');
        //如果没有登录则直接登录.
        if(empty($me_name)) {
            $this->load->model('auth_model');
            $this->auth_model->loginpush($me_id);
        }
        $time = time();
        $ip = $this->input->ip_address();
        $final_result = false;
        $this->db->trans_begin();

        $this->load->library('util');
        $order_no = Util::genOrderNumber();
        //$order_no = $this->input->post('o_number');
        $confirm_code = rand(1, 9) . rand(1, 9) . rand(1, 9) . rand(1, 9) . rand(1, 9) . rand(1, 9);
        $type = $this->input->post('o_servicetype');
        log_message('error', 'parserDataCreateOrder ' . ($data) . 'service_type ' . $type . ' ' . $order_no . ' ip ' . $ip.' me_id '.$me_id.' ');
        $this->db->query("INSERT INTO orders SET order_number='{$order_no}',merchant_id={$me_id},service_category=1,service_type={$type},add_time={$time},order_type=1,push_time={$time},confirm_code={$confirm_code}");
        $order_id = $this->db->insert_id();

        /**
         * 创建订单详情
         */
        //组合省市区文案
        $areas = getAreas();
        $area_names = [];
        foreach ($areas as $area) {
            $area_names[$area['n']] = $area;
        }

        $address = explode(' ', $this->input->post('o_custaddress'));
        $customer_city='';
        $customer_province='';

        if (count($address) == 4) {
            $customer_area = $address[2];
            $customer_city = $address[1];
            $customer_province = $address[0];
            $customer_area_id = @$area_names[$customer_area]['i'] ?: 0;
        } else if (count($address) == 3) {
            $customer_area = $address[1];
            $customer_city = $address[0];
            $customer_area_id = @$area_names[$customer_area]['i'] ?: 0;
        } else {
            $customer_area_id = 0;
        }
        log_message('error', 'parserDataCreateOrder d '.$customer_area.' customer_area_id '.$customer_area_id);
        //客户信息
        @$district = $areas[$customer_area_id];
        @$city = $areas[$district['p']];
        @$province = $areas[$city['p']];
        log_message('error', 'parserDataCreateOrder ddddd '.$customer_city.' customer_area_id '.$city['n'].strcmp($customer_city,$city['n']));

        if((strcmp($customer_city,$city['n'])||strcmp($customer_province,$province['n']))) {
            //无法从area.php 获取真确的省份列表,要查询数据库
            $this->load->model('province_model');
            $customer_area_id = $this->province_model->getAddress($customer_area,$customer_city);
            @$district = $areas[$customer_area_id];
            @$city = $areas[$district['p']];
            @$province = $areas[$city['p']];
        }
        @$customer_area = implode('-', [$province['n'], $city['n'], $district['n']]);

        $customer_name = $this->input->post('o_customer');
        $customer_phone = $this->input->post('o_custphone');
        $customer_address = $this->input->post('o_custaddress');
        log_message('error', 'parserDataCreateOrder d '.$district['p'].' area '.$customer_area.' adress '.$customer_address);
        $elevater = $this->input->post('o_elevator');
        $floor = $this->input->post('o_floor');
        $tmall_number = $this->input->post('o_checknumber');
        $customer_remark = $this->input->post('o_memark');

        //物流信息
        $goodnum=$this->input->post('o_logisticsnum');//货品数
        $logistics_no=$this->input->post('o_logisticsnumber');
        $logistics_name='';//物流公司名称
        $logistics_phone=$this->input->post('o_logiphone');
        $logistics_address=$this->input->post('o_logistiaddress');
        $logistics_consignee=$this->input->post('o_logisname');//收货人姓名
        $logistics_remark=$this->input->post('o_logimark');
        //下单信息
        $me_name=$this->session->userdata('me_username');
        $me_phone=$this->session->userdata('me_phone');
        $hope_finish_time=$this->input->post('');
        $requirements='';

        $cargo_arrive=$this->input->post('o_logistatus');//是否到货;

        //更新orders_detail
        $this->db->query("INSERT INTO orders_detail SET order_id={$order_id},customer_name='{$customer_name}',customer_phone='{$customer_phone}',customer_area_id='{$customer_area_id}',customer_address='{$customer_address}',customer_elevator={$elevater},customer_floor={$floor},customer_tmall_number='{$tmall_number}',customer_memark='{$customer_remark}',logistics_packages={$goodnum},logistics_ticketnumber='{$logistics_no}',logistics_name='{$logistics_name}',logistics_phone='{$logistics_phone}',logistics_address='{$logistics_address}',logistics_consignee='{$logistics_consignee}',logistics_mark='{$logistics_remark}',merchant_name='{$me_name}',merchant_phone='{$me_phone}',merchant_finish_time='{$hope_finish_time}',add_time={$time},merchant_requirements='{$requirements}',customer_area='{$customer_area}'");
        //更新orders_status
        $this->db->query("INSERT INTO orders_status SET order_id={$order_id},merchant_status=1,logistics_status={$cargo_arrive},add_time={$time}");


        // 物品信息goods
        $cargolistid = json_decode($this->input->post('o_cargolistid'),true);//ID
        $cargolistname = json_decode($this->input->post('o_cargolistname'),true);//名称
        $cargolistnum = json_decode($this->input->post('o_cargolistnum'),true);//数量
        $cargolistcat = json_decode($this->input->post('o_cargolistcat'),true);//类目
        $cargolistprice = json_decode($this->input->post('o_cargolistprice'),true);//价格
        $cargolistimg = json_decode($this->input->post('o_cargolistimg'),true);//图片
        $crgolistps = json_decode($this->input->post('o_cargolistps'),true);//备注


        $insert_value = '';
        $img_host = 'http://shangjia.lebangdaojia.com/upload/';
        $this->load->helper('qiniu');

        foreach($cargolistid as $key=>$value) {
            $imgvalue = $img_host.$cargolistimg[$key];
            $qiniupath = saveUrl($imgvalue);
            //log_message('error', 'parserDataCreateOrder img qiniu '.$qiniupath.' imgpath '.$imgvalue);
            $insert_value .= "(null,{$order_id},{$value},{$cargolistcat[$key]},'{$cargolistname[$key]}','{$crgolistps[$key]}',{$cargolistnum[$key]},'{$qiniupath}','$cargolistprice[$key]',{$time},0),";
        }

        $insert_value = rtrim($insert_value, ',');
        //log_message('error', 'parserDataCreateOrder img all '.$insert_value);
        $this->db->query("INSERT INTO orders_goods VALUES {$insert_value}");

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
            $final_result = true;
        }

        $ret =  $final_result ? $order_id : false;
        log_message('error','final result '.$ret);
        if($ret){
            //此处exec，推送订单消息
            $arr = array(
                'order_id' => $ret,
                'area_id' => $customer_area_id,
                'service_type' => $type
            );
            $cmd = '/usr/bin/php index.php task push_master "'. urlencode(serialize($arr)) .'" > /dev/null &';
            exec($cmd);
        }

        return $ret;
    }

}